//
//  HSFLocationVC.m
//  SellItemDemo
//
//  Created by 黄山锋 on 2018/1/3.
//  Copyright © 2018年 panlong. All rights reserved.
//

#import "HSFLocationVC.h"

@interface HSFLocationVC ()<MKMapViewDelegate,CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *locationLabel;
@property (weak, nonatomic) IBOutlet UILabel *lngLabel;
@property (weak, nonatomic) IBOutlet UILabel *latLabel;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (nonatomic,strong) CLLocationManager *locationManager;
//目标位置
@property (weak, nonatomic) IBOutlet UIImageView *targetImgView;

@property (nonatomic,strong) NSString *province;
@property (nonatomic,strong) NSString *city;
@property (nonatomic,strong) NSString *county;

@end

@implementation HSFLocationVC
#pragma mark viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"地图选址";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.targetImgView.center = self.mapView.center;
    
    //初始化定位manager
    [self initLocationManager];
    //初始化mapView
    [self initMapView];
    
    //回到我的位置
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"我的位置" style:UIBarButtonItemStylePlain target:self action:@selector(backToUserLocation)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];

}

//初始化定位manager
-(void)initLocationManager{
    self.locationManager = [[CLLocationManager alloc]init];
    //判断当前设备定位服务是否打开
    if (![CLLocationManager locationServicesEnabled]) {
        NSString *message = @"您的手机目前未开启定位服务，如欲开启定位服务，请至设定开启定位服务功能";
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"无法定位" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
    }
    
    //判断当前设备版本大于iOS8以后的话执行里面的方法
    if ([UIDevice currentDevice].systemVersion.floatValue >=8.0) {
        //持续授权
        // [locationManager requestAlwaysAuthorization];
        //当用户使用的时候授权
        [self.locationManager requestWhenInUseAuthorization];
    }
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        
        NSString *message = @"您的手机目前未开启定位服务，如欲开启定位服务，请至设定开启定位服务功能";
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"无法定位" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        
    }
    // 设置代理
    self.locationManager.delegate = self;
    // 设置定位精确度到米
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置过滤器为无
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    // 开始定位
    [self.locationManager startUpdatingLocation];

}
//初始化mapView
-(void)initMapView{
    /*
     MKUserTrackingModeNone  不进行用户位置跟踪
     MKUserTrackingModeFollow  跟踪用户的位置变化
     MKUserTrackingModeFollowWithHeading  跟踪用户位置和方向变化
     */
    //设置用户的跟踪模式
    self.mapView.userTrackingMode = MKUserTrackingModeNone;
    /*
     MKMapTypeStandard  标准地图
     MKMapTypeSatellite    卫星地图
     MKMapTypeHybrid      鸟瞰地图
     MKMapTypeSatelliteFlyover
     MKMapTypeHybridFlyover
     */
    self.mapView.mapType = MKMapTypeStandard;
    //不显示罗盘
    self.mapView.showsCompass = NO;
    //不显示比例尺
    self.mapView.showsScale = NO;
    //实时显示交通路况
    self.mapView.showsTraffic=NO;
    //设置代理
    self.mapView.delegate=self;
    //设置地图可缩放
    self.mapView.zoomEnabled = YES;
    //设置地图可滚动
    self.mapView.scrollEnabled = YES;
    //设置地图可旋转
    self.mapView.rotateEnabled = YES;
    //设置显示用户显示位置
    self.mapView.showsUserLocation = YES;
    //为MKMapView设置delegate
    self.mapView.delegate = self;
//    //设置地图显示范围
//    MKCoordinateSpan span=MKCoordinateSpanMake(0.1, 0.1);
//    //定位到用户当前位置
//    [self.mapView setRegion:MKCoordinateRegionMake(self.mapView.userLocation.coordinate, span) animated:YES];
}
//回到我的位置
-(void)backToUserLocation{
    CLLocationCoordinate2D coordinate = self.mapView.userLocation.coordinate;
    MKCoordinateSpan span = {0.1,0.1};
    MKCoordinateRegion region = {coordinate,span};
    [self.mapView setRegion:region animated:YES];
}

#pragma mark 点击事件
//点击确认
- (IBAction)sureBtnACTION:(UIButton *)sender {
    if ([self.delegate respondsToSelector:@selector(locationVC:sureLocation:lat:lng:province:city:county:)]) {
        [self.delegate locationVC:self sureLocation:self.locationLabel.text lat:self.latLabel.text lng:self.lngLabel.text province:self.province city:self.city county:self.county];
    }
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark 代理方法
#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //设置显示区域
    CLLocationCoordinate2D coordinate = newLocation.coordinate;
    MKCoordinateSpan span = {0.1,0.1};
    MKCoordinateRegion region = {coordinate,span};
    [self.mapView setRegion:region animated:YES];
    //停止定位
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [manager stopUpdatingLocation];
    });
    
}
#pragma mark MKMapViewDelegate
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        CLLocationCoordinate2D coordinate = self.mapView.userLocation.coordinate;
        MKCoordinateSpan span = {0.1,0.1};
        MKCoordinateRegion region = {coordinate,span};
        [self.mapView setRegion:region animated:YES];
    });
}
//当MKMapView显示区域将要发生改变时激发该方法
-(void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    NSLog(@"地图控件的显示区域要发生改变");
}
//当MKMapView显示区域改变完成时激发该方法
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    NSLog(@"地图控件完成了改变");
    CLLocationCoordinate2D centerCoordinate = mapView.centerCoordinate;
    self.latLabel.text = [NSString stringWithFormat:@"%f",centerCoordinate.latitude];
    self.lngLabel.text = [NSString stringWithFormat:@"%f",centerCoordinate.longitude];
    //反向地理编码
    CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
    CLLocation *cl = [[CLLocation alloc] initWithLatitude:centerCoordinate.latitude longitude:centerCoordinate.longitude];
    __block typeof(self) weakSelf = self;
    [clGeoCoder reverseGeocodeLocation:cl completionHandler: ^(NSArray *placemarks,NSError *error) {
//        for (CLPlacemark *placeMark in placemarks) {
//            NSDictionary *addressDic = placeMark.addressDictionary;
//            NSString *state=[addressDic objectForKey:@"State"];
//            NSString *city=[addressDic objectForKey:@"City"];
//            NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
//            NSString *street=[addressDic objectForKey:@"Street"];
//
//            NSLog(@"所在城市====%@ %@ %@ %@", state, city, subLocality, street);
//        }
        
        
        
        CLPlacemark *placemark = [placemarks objectAtIndex:0];
        NSString *address = placemark.addressDictionary[@"FormattedAddressLines"][0];
        NSString *address_detail = placemark.name;
        if (kStringIsEmpty(address_detail)) {
            address_detail = @"";
        }
        NSString *address_all = [NSString stringWithFormat:@"%@%@",address, address_detail];
        weakSelf.locationLabel.text = address_all;
        
        
        NSDictionary *addressDic = placemark.addressDictionary;
        NSString *state=[addressDic objectForKey:@"State"];
        NSString *city=[addressDic objectForKey:@"City"];
        NSString *subLocality=[addressDic objectForKey:@"SubLocality"];
        NSString *street=[addressDic objectForKey:@"Street"];
        
        if (kStringIsEmpty(city)) {
            city = subLocality;
        }
        if (kStringIsEmpty(state)) {
            state = city;
        }
        
        self.province = state;
        self.city = city;
        self.county = subLocality;
    }];
}
//当地图控件MKMapView开始加载数据时激发该方法
-(void)mapViewWillStartLoadingMap:(MKMapView *)mapView
{
    NSLog(@"地图控件开始加载地图数据");

    
}
//当MKMapView加载数据完成时激发该方法
-(void)mapViewDidFinishLoadingMap:(MKMapView *)mapView
{
    NSLog(@"地图控件加载地图数据完成");
    NSLog(@"%@",mapView);
}
//当MKMapView加载数据失败时激发该方法
-(void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error
{
    NSLog(@"地图控件加载地图数据发生错误：错误信息：%@",error);
}
//当MKMapView开始渲染地图时激发该方法
-(void)mapViewWillStartRenderingMap:(MKMapView *)mapView
{
    NSLog(@"地图控件开始渲染地图");
}
//当MKMapView渲染地图完成时激发该方法
-(void)mapViewDidFinishRenderingMap:(MKMapView *)mapView fullyRendered:(BOOL)fullyRendered
{
    NSLog(@"地图控件渲染完成");
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
